package com.Policing.Check;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;

import com.Policing.Since_case.Since_case;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.bean.Input_item;
import com.Policing.bean.Issued_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;


import com.senter.iot.support.openapi.uhf.UhfD2;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/22.
 */

public class Check extends Activity implements OnDismissListener {
    private String checkdetailIds;//单号，状态
    private Handler handler = new Handler();
    private ListView listView;
    private LinearLayout hidden,Sliding,cut_lv;
    private Button scan,submit,cut,pda;//扫码，上传,rfid
    private String id,userId;
    ProgressDialog pd;
    int i = 0;
    int progressBarMax = 100;
    private int star=0;
    private String query_url = "http://"+ Ip_Set.IP+"/api/checkAssetScanQuery";
    private LoadingDialog loadingDialog;
    private List<String> plan =  new ArrayList<>();//待盘点
    private List<String> reality =  new ArrayList<>();//已盘点
    private List<String> surplus =  new ArrayList<>();//盘盈
    private List<String> deficit =  new ArrayList<>();//盘亏
    private String url = "http://"+ Ip_Set.IP+"/api/checkdetailQueryByIds";
    private String upload_url = "http://"+ Ip_Set.IP+"/api/assetCheck";
    private String add_br = "http://"+ Ip_Set.IP+"/api/checkTextAdd";
    private LinearLayout For,Have,profit,losses;//待盘点，已盘点，盘盈，盘亏
    private List<Input_item> For_data = new ArrayList<>();
    private List<Input_item> Have_data = new ArrayList<>();
    private List<Input_item> profit_data = new ArrayList<>();
    private Input_Adapter_item adapter_item;
    private boolean stop_rfid =true;
    private boolean isrfid=true;
    private boolean state;
    private EditText et_num;
    private List<String> rfid_data = new ArrayList<>();
    private List<Input_item> losses_data = new ArrayList<>();
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(Check.this, R.raw.tag_inventoried);
    private Handler accompainimentsHandler;
    private TextView odd,createuser,sum,createdate,date;//盘点单号，创建人，应盘总数，创建日期，完成日期
    private TextView For_inventory,Have_inventory,inventory_profit,inventory_losses;//待盘点，已盘点，盘盈，盘亏
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_main);

        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        userId = mm.getString("id","");
        inview();
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("加载中....");
        loadingDialog.show();
        Load_data();
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(firstVisibleItem==0){
                    hidden.setVisibility(View.VISIBLE);
                    Sliding.setVisibility(View.VISIBLE);
                  //  Log.e("log", "滑到顶部");
                }
                if(visibleItemCount+firstVisibleItem==totalItemCount){
                    Log.e("log", "滑到底部");
                }
            }
        });
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 触摸按下时的操作
                        hidden.setVisibility(View.GONE);
                        Sliding.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 触摸移动时的操作

                        break;
                    case MotionEvent.ACTION_UP:
                        // 触摸抬起时的操作

                        break;
                }
                return false;
            }
        });
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, Check.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            for (int i=0;i<For_data.size();i++){
                                plan.add(For_data.get(i).getCode_number());
                            }
                            for (int i=0;i<Have_data.size();i++){
                                reality.add(Have_data.get(i).getCode_number());
                            }
                            for (int i=0;i<profit_data.size();i++){
                                surplus.add(profit_data.get(i).getCode_number());
                            }
                            for (int i=0;i<losses_data.size();i++){
                                deficit.add(losses_data.get(i).getCode_number());
                            }
                            pd=new ProgressDialog(Check.this);
                            pd.setMessage("上传数据中...");//设置消息
                            pd.setMax(100);//设置进度条的最大值
                            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);;
                            pd.setCancelable(false);//这是是否可撤销/也就是这个对话框是否可以关闭
                            pd.setIndeterminate(false);//设置是否是确定值
                            pd.show();//展示对话框
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    while (i++ < progressBarMax) {
                                        //设置滚动条当前状态值
                                        pd.setProgress(i);
                                        try {
                                            Thread.sleep(600);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                            upload();
                        }
                        if (position==-1){
                        }
                    }
                }).setCancelable(true).setOnDismissListener(Check.this).show();

            }
        });
    /*    bt_Rfid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(Check.this,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    bt_Rfid.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    bt_Rfid.setText("开启RFID");
                }

            }
        });*/


    }
    private void show(final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(Check.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("userId",userId)
                        .add("surplus",surplus.toString())
                        .add("deficit",deficit.toString())
                        .add("plan",plan.toString())
                        .add("reality",reality.toString())
                        .add("checkId",id)

                        .add("source", Since_case.set().getSource())

                        .add("checkdetailIds",checkdetailIds); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(upload_url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        show("提交失败，请检查网络");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1")){
                                        Toast.makeText(Check.this,"提交成功",Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(Check.this,Check_choose.class);
                                        intent.putExtra("checkId",id);
                                        startActivity(intent);
                                        finish();
                                    }
                                    if (json.getString("state").equals("0")){
                                        pd.cancel();
                                        show("提交失败");
                                    }
                                } catch (JSONException e) {
                                    pd.cancel();
                                    show("服务器带标物资存在无编号或者编号重复");
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }
    private void Load_data() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("source",Since_case.set().getSource())
                        .add("checkdetailIds",checkdetailIds); //传递键值对参数
                final Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Check.this,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("CheckCheckCheck",responseData);
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    createuser.setText(jsonObject.getString("createuser"));
                                    sum.setText(jsonObject.getString("sum"));
                                    if (jsonObject.getString("createdate").equals("")){
                                        createdate.setText(jsonObject.getString("createdate"));
                                    }else
                                    createdate.setText(jsonObject.getString("createdate").substring(0,10));
                                    date.setText(jsonObject.getString("date"));
                                    For_inventory.setText(jsonObject.getString("num1"));
                                    Have_inventory.setText(jsonObject.getString("num2"));
                                    inventory_profit.setText(jsonObject.getString("num3"));
                                    inventory_losses.setText(jsonObject.getString("num4"));
                                    JSONArray jsonarray = jsonObject.getJSONArray("assets1");
                                    JSONArray jsonarray1 = jsonObject.getJSONArray("assets2");
                                    JSONArray jsonarray2 = jsonObject.getJSONArray("assets3");
                                    JSONArray jsonarray3 = jsonObject.getJSONArray("assets4");
                                    Bitmap bitmap =null;
                                    if (!jsonarray.equals("[]")){
                                        Gson gson = new Gson();
                                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonarray), new TypeToken<List<Issued_bean>>(){}.getType());
                                        for(int i = 0;i < userList.size();i++){
                                            String assetName = userList.get(i).getAssetName();
                                            String deptId = userList.get(i).getDeptId();
                                            String assetNumber =userList.get(i).getAssetNumber();
                                            String userId = userList.get(i).getUserId();
                                            String model = userList.get(i).getModel();
                                            String type = userList.get(i).getType();
                                            String rfid = userList.get(i).getRfid();
                                            if (userList.get(i).getImage().equals("")){// wh getResources().openRawResource(R.mipmap.null_po);
                                                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                bitmap = BitmapFactory.decodeStream(is);
                                            }else {
                                                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                                                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                            }
                                            For_data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,rfid));

                                        }
                                        adapter_item = new Input_Adapter_item(Check.this,R.layout.input_adapter_item,For_data);
                                        listView.setAdapter(adapter_item);
                                    }
                                    if (!jsonarray1.equals("[]")){
                                        Gson gson = new Gson();
                                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonarray1), new TypeToken<List<Issued_bean>>(){}.getType());
                                        for(int i = 0;i < userList.size();i++){
                                            String assetName = userList.get(i).getAssetName();
                                            String deptId = userList.get(i).getDeptId();
                                            String assetNumber =userList.get(i).getAssetNumber();
                                            String userId = userList.get(i).getUserId();
                                            String model = userList.get(i).getModel();
                                            String type = userList.get(i).getType();
                                            if (userList.get(i).getImage().equals("")){// wh getResources().openRawResource(R.mipmap.null_po);
                                                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                bitmap = BitmapFactory.decodeStream(is);
                                            }else {
                                                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                                                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                            }
                                            Have_data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
                                        }

                                    }
                                    if (!jsonarray2.equals("[]")){
                                        Gson gson = new Gson();
                                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonarray2), new TypeToken<List<Issued_bean>>(){}.getType());
                                        for(int i = 0;i < userList.size();i++){
                                            String assetName = userList.get(i).getAssetName();
                                            String deptId = userList.get(i).getDeptId();
                                            String assetNumber =userList.get(i).getAssetNumber();
                                            String userId = userList.get(i).getUserId();
                                            String model = userList.get(i).getModel();
                                            String type = userList.get(i).getType();
                                            String rfid = userList.get(i).getRfid();
                                            if (userList.get(i).getImage().equals("")){// wh     InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                bitmap = BitmapFactory.decodeStream(is);
                                            }else {
                                                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                                                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                            }
                                            profit_data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,rfid));
                                        }
                                    }
                                    if (!jsonarray3.equals("[]")){
                                        Gson gson = new Gson();
                                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonarray3), new TypeToken<List<Issued_bean>>(){}.getType());
                                        for(int i = 0;i < userList.size();i++){
                                            String assetName = userList.get(i).getAssetName();
                                            String deptId = userList.get(i).getDeptId();
                                            String assetNumber =userList.get(i).getAssetNumber();
                                            String userId = userList.get(i).getUserId();
                                            String model = userList.get(i).getModel();
                                            String type = userList.get(i).getType();
                                            String rfid = userList.get(i).getRfid();
                                            if (userList.get(i).getImage().equals("")){ // wh InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                bitmap = BitmapFactory.decodeStream(is);
                                            }else {
                                                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                                                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                            }
                                            losses_data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,rfid));
                                        }
                                    }
                                    loadingDialog.dismiss();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Log.i("responseData",responseData);
                            }
                        });

                    }
                });

            }
        }).start();
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void inview() {
        pda = (Button) findViewById(R.id.pda);
        cut = (Button) findViewById(R.id.cut);
        cut_lv= (LinearLayout) findViewById(R.id.cut_lv);
        et_num = (EditText) findViewById(R.id.et_num);
        //et_num.setInputType(InputType.TYPE_NULL);
        et_num.setShowSoftInputOnFocus(false);
       // bt_Rfid = (Button) findViewById(R.id.Rfid);
        Sliding = (LinearLayout) findViewById(R.id.Sliding);
        hidden = (LinearLayout) findViewById(R.id.hidden);
        listView = (ListView) findViewById(R.id.fragment2_list);
        losses = (LinearLayout) findViewById(R.id.losses);
        profit = (LinearLayout) findViewById(R.id.profit);
        For = (LinearLayout) findViewById(R.id.For);
        Have = (LinearLayout) findViewById(R.id.Have);
        Intent intent = getIntent();
        checkdetailIds = intent.getStringExtra("checkId");
        id = intent.getStringExtra("id");
        Log.i("checkId",checkdetailIds);
        scan = (Button) findViewById(R.id.scan);
        submit = (Button) findViewById(R.id.submit);
        odd = (TextView) findViewById(R.id.odd);
        odd.setText(id);
        createuser = (TextView) findViewById(R.id.createuser);
        sum = (TextView) findViewById(R.id.sum);
        createdate = (TextView) findViewById(R.id.createdate);
        date = (TextView) findViewById(R.id.date);
        For_inventory = (TextView) findViewById(R.id.For_inventory);
        For_inventory.setTextColor(Color.parseColor("#00FF00"));
        pda.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cut_lv.setVisibility(View.VISIBLE);
                hidden.setVisibility(View.GONE);
            }
        });
        cut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cut_lv.setVisibility(View.GONE);
                hidden.setVisibility(View.VISIBLE);
            }
        });
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                et_num.selectAll();
                int stutas =0;
                for (int i = 0; i<Have_data.size();i++){
                    if (et_num.getText().toString().trim().equals(Have_data.get(i).getCode_number())){
                        Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                        stutas=1;
                        return;
                    }
                }

                for (int i = 0; i<profit_data.size();i++){
                    if (et_num.getText().toString().trim().equals(profit_data.get(i).getCode_number())){
                        stutas=1;
                        Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                for (int i = 0; i<For_data.size();i++){
                    if (et_num.getText().toString().trim().equals(For_data.get(i).getCode_number())){
                        Have_data.add(For_data.get(i));
                        stutas=1;
                        For_data.remove(i);
                    }
                }
                for (int i = 0; i<losses_data.size();i++){
                    if (et_num.getText().toString().trim().equals(losses_data.get(i).getCode_number())){
                        Have_data.add(losses_data.get(i));
                        stutas=2;
                        losses_data.remove(i);
                    }
                }
                Log.i("stutasstutas", String.valueOf(stutas));
                if (stutas==0){
                    stutas=0;                    Log.i("stutasstutas", String.valueOf(stutas));
                    query(et_num.getText().toString().trim(),"");
                }else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter_item.notifyDataSetChanged();
                            Have_inventory.setText(String.valueOf(Have_data.size()));
                            For_inventory.setText(String.valueOf(For_data.size()));
                            inventory_profit.setText(String.valueOf(profit_data.size()));
                            inventory_losses.setText(String.valueOf(losses_data.size()));
                        }
                    });

                }
            }
        });
        For.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                star = 0;
                For_inventory.setTextColor(Color.parseColor("#00FF00"));
                Have_inventory.setTextColor(Color.parseColor("#000000"));
                inventory_profit.setTextColor(Color.parseColor("#3794fc"));
                inventory_losses.setTextColor(Color.parseColor("#FF0000"));
                adapter_item = new Input_Adapter_item(Check.this,R.layout.input_adapter_item,For_data);
                listView.setAdapter(adapter_item);
            }
        });
        Have_inventory = (TextView) findViewById(R.id.Have_inventory);
        Have.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                star = 1;
                Have_inventory.setTextColor(Color.parseColor("#00FF00"));
                For_inventory.setTextColor(Color.parseColor("#000000"));
                inventory_profit.setTextColor(Color.parseColor("#3794fc"));
                inventory_losses.setTextColor(Color.parseColor("#FF0000"));
                adapter_item = new Input_Adapter_item(Check.this,R.layout.input_adapter_item,Have_data);
                listView.setAdapter(adapter_item);
            }
        });
        inventory_profit  = (TextView) findViewById(R.id.inventory_profit);
        profit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                star = 2;
                inventory_profit.setTextColor(Color.parseColor("#00FF00"));
                For_inventory.setTextColor(Color.parseColor("#000000"));
                Have_inventory.setTextColor(Color.parseColor("#000000"));
                inventory_losses.setTextColor(Color.parseColor("#FF0000"));
                adapter_item = new Input_Adapter_item(Check.this,R.layout.input_adapter_item,profit_data);
                listView.setAdapter(adapter_item);
            }
        });
        inventory_losses = (TextView) findViewById(R.id.inventory_losses);
        losses.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                star = 0;
                inventory_losses.setTextColor(Color.parseColor("#00FF00"));
                For_inventory.setTextColor(Color.parseColor("#000000"));
                Have_inventory.setTextColor(Color.parseColor("#000000"));
                inventory_profit.setTextColor(Color.parseColor("#3794fc"));
                adapter_item = new Input_Adapter_item(Check.this,R.layout.input_adapter_item,losses_data);
                listView.setAdapter(adapter_item);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (star==1){
                    Intent intent1 = new Intent(Check.this,Check_alter.class);
                    intent1.putExtra("AssetName",Have_data.get(position).getAsset_name());
                    intent1.putExtra("AssetNumber",Have_data.get(position).getCode_number());
                    intent1.putExtra("DeptId",Have_data.get(position).getSection());
                    intent1.putExtra("preserver",Have_data.get(position).getCustodian());
                    intent1.putExtra("Type",Have_data.get(position).getModel());
                    startActivityForResult(intent1,1);
                }
                if (star==2){
                    Intent intent1 = new Intent(Check.this,Check_alter.class);
                    intent1.putExtra("AssetName",profit_data.get(position).getAsset_name());
                    intent1.putExtra("AssetNumber",profit_data.get(position).getCode_number());
                    intent1.putExtra("DeptId",profit_data.get(position).getSection());
                    intent1.putExtra("preserver",profit_data.get(position).getCustodian());
                    intent1.putExtra("Type",profit_data.get(position).getModel());
                    startActivityForResult(intent1,2);
                }
            }
        });
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Check.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            int stutas =0;
            for (int i = 0; i<Have_data.size();i++){
                if (scanResult.equals(Have_data.get(i).getCode_number())){
                    Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                    stutas=1;
                    return;
                }
            }

            for (int i = 0; i<profit_data.size();i++){
                if (scanResult.equals(profit_data.get(i).getCode_number())){
                    stutas=1;
                    Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            for (int i = 0; i<losses_data.size();i++){
                if (scanResult.equals(losses_data.get(i).getCode_number())){
                    Have_data.add(losses_data.get(i));
                    stutas=2;
                    losses_data.remove(i);
                }
            }
            for (int i = 0; i<For_data.size();i++){
                if (scanResult.equals(For_data.get(i).getCode_number())){
                    Have_data.add(For_data.get(i));
                    stutas=1;
                    For_data.remove(i);
                }
            }
            Log.i("stutasstutas", String.valueOf(stutas));
            if (stutas==0){
                stutas=0;
                Log.i("stutasstutas", String.valueOf(stutas));
                query(scanResult,"");
            }else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter_item.notifyDataSetChanged();
                        Have_inventory.setText(String.valueOf(Have_data.size()));
                        For_inventory.setText(String.valueOf(For_data.size()));
                        inventory_profit.setText(String.valueOf(profit_data.size()));
                        inventory_losses.setText(String.valueOf(losses_data.size()));
                    }
                });

            }



        }
        if (requestCode==2&&resultCode==6){
            for (int i =0;i<profit_data.size();i++){
                if (profit_data.get(i).getCode_number().equals(data.getExtras().getString("AssetNumber")))
                    profit_data.get(i).setCustodian(data.getExtras().getString("preserver"));
                profit_data.get(i).setSection(data.getExtras().getString("DeptId"));
                profit_data.get(i).setCategory(data.getExtras().getString("place"));
                adapter_item.notifyDataSetChanged();
            }
        }
        if (requestCode==1&&resultCode==6){
            for (int i =0;i<Have_data.size();i++){
               if (Have_data.get(i).getCode_number().equals(data.getExtras().getString("AssetNumber")))
                   Have_data.get(i).setCustodian(data.getExtras().getString("preserver"));
                    Have_data.get(i).setSection(data.getExtras().getString("DeptId"));
                    Have_data.get(i).setCategory(data.getExtras().getString("place"));
                    adapter_item.notifyDataSetChanged();
            }
        }
    }

    private void query(final String assetNumber, final String RFID) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",assetNumber)
                        .add("rfid",RFID)
                        .add("source",Since_case.set().getSource())
                        .add("checkdetailIds",checkdetailIds); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(query_url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject json = new JSONObject(responseData);
                                    Log.i("stutasstutas", String.valueOf(json));
                                    if (json.getString("state").equals("1")){
                                        Bitmap bitmap =null;
                                        JSONObject jsonObject = json.getJSONObject("asset");
                                            String assetName = jsonObject.getString("assetName");
                                            String deptId = jsonObject.getString("deptId");
                                            String assetNumber = jsonObject.getString("assetNumber");
                                            String userId = jsonObject.getString("userId");
                                            String model = jsonObject.getString("model");
                                            String type = jsonObject.getString("type");
                                            String rfid = jsonObject.getString("rfid");
                                            if (jsonObject.getString("image").equals("")){ // wh  getResources().openRawResource(R.mipmap.null_po)
                                                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                                bitmap = BitmapFactory.decodeStream(is);
                                            }else {
                                                byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                            }
                                        profit_data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,rfid));
                                        adapter_item.notifyDataSetChanged();
                                        Have_inventory.setText(String.valueOf(Have_data.size()));
                                        For_inventory.setText(String.valueOf(For_data.size()));
                                        inventory_profit.setText(String.valueOf(profit_data.size()));
                                        inventory_losses.setText(String.valueOf(losses_data.size()));
                                    }
                                    if (json.getString("state").equals("0")){
                                        Toast.makeText(Check.this,"提交失败",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("2")){
                                        Toast.makeText(Check.this,"资产不存在",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("3")){
                                        Toast.makeText(Check.this,"类别错误",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("4")){
                                        Toast.makeText(Check.this,"部门错误",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }
    @Override
    public void onDismiss(Object o) {

    }
    public void add_remarks(final String remark){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("text",remark)
                        .add("checkId",id)
                        .add("source",Since_case.set().getSource());//传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(add_br)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1")){
                                        Toast.makeText(Check.this,"提交成功",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("0")){
                                        Toast.makeText(Check.this,"提交失败",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    //将扫描出的信息显示出来
                    int stutas =0;
                    for (int i = 0; i<Have_data.size();i++){
                        if (rfid.equals(Have_data.get(i).getRfid())){
                            Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                          stutas=1;
                            return;
                        }
                    }

                    for (int i = 0; i<profit_data.size();i++){
                        if (rfid.equals(profit_data.get(i).getRfid())){
                            stutas=1;
                            Toast.makeText(Check.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    for (int i = 0; i<For_data.size();i++){
                        if (rfid.equals(For_data.get(i).getRfid())){
                            Have_data.add(For_data.get(i));
                            stutas=1;
                            For_data.remove(i);
                        }
                    }
                    for (int i = 0; i<losses_data.size();i++){
                        if (rfid.equals(losses_data.get(i).getRfid())){
                            Have_data.add(losses_data.get(i));
                            stutas=2;
                            losses_data.remove(i);
                        }
                    }
                    Log.i("stutasstutas", String.valueOf(stutas));
                    if (stutas==0){
                        stutas=0;
                        Log.i("stutasstutas", String.valueOf(stutas));
                        query("",rfid);
                    }else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                adapter_item.notifyDataSetChanged();
                                Have_inventory.setText(String.valueOf(Have_data.size()));
                                For_inventory.setText(String.valueOf(For_data.size()));
                                inventory_profit.setText(String.valueOf(profit_data.size()));
                                inventory_losses.setText(String.valueOf(losses_data.size()));
                            }
                        });

                    }
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
}
